var mysql = require('mysql');
let { host, port, user, password, database, multipleStatements } = require('./config');
let CreateTable = require('./CreateTable');
let InsertData = require('./InsertData');

let connection = null;
let createConnection_ = async function () {
    // mysqljs 连接 mysql，但是不链接MySQL数据库
    connection = await mysql.createConnection({
        host,
        port,
        user, // mysql的用户名
        password, // mysql的密码
        multipleStatements, // 多语句执行
    })
}

async function changeUser() {
    // 更改链接信息。链接到对应的数据库
    await connection.changeUser({
        host,
        port,
        user,
        password,
        database
    }, function (err) {
        if (err) throw err;
    });
}

// 创建数据库
let createDatabase = async function (connection) {
    console.log('CreateDatabase.js ----- 创建数据库：', database)
    await connection.query(`CREATE DATABASE ${database} CHARACTER SET utf8 COLLATE utf8_general_ci`, async function (error, results, fields) {
        if (error && error.message.includes('database exists')) {
            console.log("CreateDatabase.js- 目标数据库已经存在!");
            console.log('', error)
        } else {
            console.log('CreateDatabase.js --- 创建数据库成功：', JSON.stringify(results))
        }
    });
    await changeUser();
}

module.exports = async function () {
    await createConnection_();
    // 连接 mysql
    await connection.connect(async err => {
        // err代表失败
        if (err) {
            console.log("CreateDatabase.js- 数据库连接失败");
            console.log('', err)
        } else {
            console.log("CreateDatabase.js- 数据库连接成功");
            await createDatabase(connection);
            await CreateTable(connection);
            await InsertData(connection);
        }
    })
    return connection;
}